<template>
  <div>
    <div class="top">
      <van-nav-bar title="编辑资料" left-arrow @click-left="onClickLeft" />
    </div>
    <div class="mid">
      <van-image round fit="cover" :src="userInfo.profile_photo" />
      <van-uploader :after-read="afterRead" />
    </div>
    <div class="cell">

      <van-cell title="名称" :value="userInfo.user_name" @click="changeName" is-link />

      <van-cell title="性别" @click="showGender" :value="userInfo.gender ? '男' : '女'" is-link />

      <van-popup v-model="genderShow" position="bottom" :style="{ height: '30%' }">
        <van-nav-bar title="性别" left-arrow @click-left="genderShow = false" />
        <van-cell title="男" @click="changeGenderMan" is-link />
        <van-cell title="女" @click="changeGenderWomen" is-link />
      </van-popup>

      <van-cell title="生日" @click="birthShow" :value="userInfo.create_date" is-link />

    </div>
    <van-dialog v-model="nameShow" @confirm="updateName" title="修改名称" show-cancel-button>
      <van-field v-model="editName" ref="myName" />
    </van-dialog>

    <van-popup v-model="dateShow" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="date" @confirm="updateBirth" title="选择年月日" :min-date="minDate"
        :max-date="maxDate" />
    </van-popup>
    <div class="crop-box" v-show="cropShow">
      <vueCropper ref="cropper" :img="img" autoCrop autoCropWidth="200" autoCropHeight="200" :centerBox="centerBox">
      </vueCropper>
      <van-button @click="changePhoto" type="primary">裁剪</van-button>
      <van-button style="right:0;" type="primary">取消</van-button>
    </div>
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
import router from '@/router'
import { Toast } from 'vant'
import { mapState } from 'vuex'
import { editUserInfoAPI, editPhotoAPI, userInfoAPI, QiniuTioken } from '@/api'
import moment from 'moment'
export default {
  name: 'myName',
  data() {
    return {
      nameShow: false,
      editName: '',
      dateShow: false,
      minDate: new Date(1950, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      genderShow: false,
      cropShow: false,
      img: '',
      centerBox: true,
      man: 1,
      women: 0,
      qiniu_token: '',
    }
  },
  components: {
    VueCropper
  },
  mounted() {
    this.genderateQiniuTioken()
  },
  methods: {
    // 生成七牛云token
    async genderateQiniuTioken() {
      const res = await QiniuTioken()
      console.log("七牛云生成的token", res)
      if (res.data.code == 200) {
        this.qiniu_token = res.data.data.qiniu_token
      }
    },
    // 上传头像
    // async afterRead(files) {
    //   const { file } = files
    //   const fd = new FormData()
    //   fd.append("qiniu_token", this.qiniu_token)
    //   fd.append("file", file)
    //   const res = await this.$axios.post(
    //     "http://up-z2.qiniup.com",
    //     fd,
    //   )
    //   console.log("图片上的结果>>", res.key)
    //   var img_url = "http://rcu6efhlr.hn-bkt.clouddn.com/" + res.key
    //   console.log("图片的地址>>", img_url)
    //   this.userInfo.profile_photo = img_url
    // },
    async afterRead(files) {
      // 此时可以自行将文件上传至服务器
      const { file } = files
      const fd = new FormData()
      fd.append("token", this.qiniu_token)
      fd.append("file", file)
      const res = await this.$axios.post(
        "http://upload-z2.qiniup.com",
        fd,
      )
      console.log("图片上的结果>>", res.key)
      var img_url = "http://rcu6efhlr.hn-bkt.clouddn.com/" + res.key
      console.log("图片的地址>>", img_url)
      this.userInfo.profile_photo = img_url

      // this.cropShow = true
      // console.log(file.content)
      // this.img = file.content
      this.changePhoto()
    },
    onClickLeft() {
      Toast('返回')
      router.push('/layout/mine')
    },
    showGender() {
      this.genderShow = true
    },
    birthShow() {
      this.dateShow = true
      this.currentDate = new Date(this.userInfo.create_date)
    },


    async updateBirth() {
      const normalDate = moment(this.currentDate).format('YYYY-MM-DD')
      console.log("这是啥？？？", normalDate)
      await editUserInfoAPI({ create_date: normalDate })
      this.dateShow = false
      this.$store.commit('changeUserInfo', {
        ...this.userInfo,
        create_date: normalDate
      })
    },
    changeName() {
      this.nameShow = true
      this.editName = this.userInfo.user_name
      setTimeout(() => {
        this.$refs.myName.focus()
      }, 500)
    },
    async changeGenderMan() {
      const res = await editUserInfoAPI({
        gender: this.man
      })
      this.$store.commit('changeUserInfo', {
        ...this.userInfo,
        gender: this.man
      })
      this.genderShow = false
    },
    async changeGenderWomen() {
      const res = await editUserInfoAPI({
        gender: this.women
      })
      this.$store.commit('changeUserInfo', {
        ...this.userInfo,
        gender: this.women
      })
      this.genderShow = false
    },

    // 修改昵称
    async updateName() {
      if (this.editName !== '') {
        const res = await editUserInfoAPI({ "name": this.editName })
        console.log('修改名字的响应', res)
        console.log("editName是啥???", this.editName)
        this.$store.commit('changeUserInfo', {
          ...this.userInfo,
          user_name: this.editName
        })
        this.$toast.success("修改名字成功")
      } else {
        this.$toast('请输入名称')
      }
    },

    // 修改头像
    async changePhoto() {
     // this.$refs.cropper.getCropBlob(async data => {
      //   // do something
      //   // console.log(data)
      //   const fm = new FormData()
      //   fm.append('photo', data)
      //   console.log(...fm)
      //   const res = await editPhotoAPI(fm)
      //   this.$store.commit('changeUserInfo', {
      //     ...this.userInfo,
      //     photo: res.data.data.photo
      //   })
      //   this.cropShow = false
      // })
 
      const res = await editUserInfoAPI(
        {"profile_photo":this.userInfo.profile_photo}
      )
      console.log("修改头像的响应", res)
      this.$store.commit('changeUserInfo', {
        ...this.userInfo,
        profile_photo: this.userInfo.profile_photo
      })
      this.cropShow = false

    }
  },
  computed: {
    ...mapState(['userInfo'])
  },
  async created() {
    this.$store.dispatch('getUserInfo')
  }
}
</script>

<style lang="less" scoped>
.mid {
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  .van-image {
    height: 120px;
    width: 120px;
  }

  ::v-deep .van-uploader {
    position: absolute;
    width: 100%;
    height: 100%;

    .van-uploader__wrapper {
      width: 100%;
      height: 100%;

      .van-uploader__upload {
        width: 100%;
        height: 100%;
        opacity: 0;
      }
    }
  }
}

.van-field {
  border: 1px solid #ddd;
}

.crop-box {
  height: 100vh;
  width: 100vw;
  position: fixed;
  left: 0;
  top: 0;

  .van-button {
    position: absolute;
    bottom: 0;
  }
}
</style>
